package com.erp.web.erp.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.erp.base.business.entity.AppUser;
import com.erp.base.business.entity.Area;
import com.erp.base.business.entity.City;
import com.erp.base.business.entity.ConsultQuestions;
import com.erp.base.business.entity.ExpertUser;
import com.erp.base.business.entity.Provincial;
import com.erp.base.business.entity.Region;
import com.erp.base.business.entity.Server;
import com.erp.base.business.service.AppUserService;
import com.erp.base.business.service.CityService;
import com.erp.base.business.service.ConsultQuestionsService;
import com.erp.base.business.service.ExpertUserService;
import com.erp.base.business.service.ProvincialService;
import com.erp.base.business.service.RegionService;
import com.erp.base.business.service.ServerService;
import com.erp.base.business.service.ServerUserRelService;
import com.erp.base.common.config.BootdoConfig;
import com.erp.base.common.config.Constant;
import com.erp.base.common.entity.Email;
import com.erp.base.common.entity.File;
import com.erp.base.common.service.FileService;
import com.erp.base.common.service.MailService;
import com.erp.base.common.utils.AppUserUtils;
import com.erp.base.common.utils.FileType;
import com.erp.base.common.utils.FileUtil;
import com.erp.base.common.utils.IPAddressUtil;
import com.erp.base.common.utils.IPUtils;
import com.erp.base.common.utils.JedisUtils;
import com.erp.base.common.utils.JsonMapper;
import com.erp.base.common.utils.OperationResult;

@Service
public class ErpIndexService {
	
	private final static Logger logger=LoggerFactory.getLogger(ErpIndexService.class);
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private ExpertUserService expertUserService;
	@Autowired
	private CityService cityService;
	@Autowired
	private ProvincialService provincialService;
	@Autowired
	private ConsultQuestionsService consultQuestionsService;
	@Autowired
	private ServerService serverService;
	@Autowired
	private MailService mailService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private ServerUserRelService serverUserRelService;
	@Autowired
	private FileService sysFileService;
	@Autowired
    private BootdoConfig bootdoConfig;
	
	
	public OperationResult getCity() {
		return OperationResult.buildSuccessResult("获取城市列表", cityService.findList(new City()));
	}

	public OperationResult getProvincial() {
		return OperationResult.buildSuccessResult("获取省份列表", provincialService.findList(new Provincial()));
	}

	public OperationResult getCityByProvincial(long provincialId) {
		City city=new City();
		city.setProvincialId(provincialId);
		return OperationResult.buildSuccessResult("通过省份ID获取城市列表", cityService.findList(city));
	}

	public OperationResult getIndexData(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object>data=new HashMap<String, Object>();
		//获取问题列表
		List<ConsultQuestions> questionLists = consultQuestionsService.findAllQuestions();
		data.put("questionLists", questionLists);
		
		//获取专家列表
		List<ExpertUser> expertUserLists = expertUserService.findExperts();
		//按照serverId 分组
		Map<String, List<ExpertUser>> expertUserGrByList = expertUserLists.stream().collect(Collectors.groupingBy(ExpertUser::getServerId));
		data.put("expertUserGrByList", expertUserGrByList);
		
		/*//城市列表
		//List<City> cityLists = cityService.findList(new City());
		List<Region> cityLists = regionService.findList(new Region());
		data.put("cityLists", cityLists);*/
		
		return OperationResult.buildSuccessResult(data);
	}

	public OperationResult getPosition(HttpServletRequest request) {
		String ip=IPUtils.getIpAddr(request);
		//ip="222.65.67.44";
		logger.info("获取请求的IP为："+ip);
		try {
			String key=Constant.REDIS_PRIFIX_ERP+ip;
			String vaule=JedisUtils.get(key);
			if(StringUtils.isBlank(vaule)){
				String result=IPAddressUtil.getAddresses(ip);
				logger.info("获取请求的result为："+result);
				Region region = regionService.findCityByShortName(result);
				if(region==null){
					return OperationResult.buildFailureResult("未能查询到对应的城市信息!");
				}
				JedisUtils.set(key, JsonMapper.toJsonString(region));
				return OperationResult.buildSuccessResult(region);
			}
			Region region=(Region) JsonMapper.fromJsonString(vaule, Region.class);
			return OperationResult.buildSuccessResult(region);
		} catch (UnsupportedEncodingException e) {
			logger.error("查询IP地址报错",e);
		}
		return OperationResult.buildFailureResult();
	}
	
	public OperationResult resetPwd(AppUser appUser,HttpServletRequest request) {
		String email=appUser.getEmail();
		if(StringUtils.isBlank(email)){
			return OperationResult.buildFailureResult("邮箱不能为空！");
		}
		String username=appUser.getUsername();
		if(StringUtils.isBlank(username)){
			return OperationResult.buildFailureResult("用户名不能为空！");
		}
		if(appUser.getCode()==null){
			return OperationResult.buildFailureResult("验证码不能为空！");
		}
		AppUser oldUser = appUserService.findAppUserByUserEmail(username,email);
		if(oldUser==null){
			return OperationResult.buildFailureResult("用户名与邮箱不匹配！");
		}
		String key=Constant.REDIS_PRIFIX_ERP+email;
		String value=JedisUtils.get(key);
		if(StringUtils.isBlank(value)){
			return OperationResult.buildFailureResult("验证码已经过期，请重新发送！");
		}
		Integer code=Integer.valueOf(value);
		if(code.compareTo(appUser.getCode())==0){
			appUser.setUpdateBy(oldUser.getUsername());
			appUser.setUpdateDate(new Date());
			appUser.setId(oldUser.getId());
			logger.info("修改密码,用户email为："+email+";用户id："+appUser.getId());
			appUserService.update(appUser);
			return OperationResult.buildSuccessResult("密码重置成功！");
		}
		return OperationResult.buildFailureResult("验证码错误！");
	}
	
	public OperationResult sendMailCode(String email,HttpServletRequest request) {
		if(StringUtils.isBlank(email)){
			return OperationResult.buildFailureResult("邮箱不能为空！");
		}
		if(appUserService.isUniqueByEmail(email)){
			return OperationResult.buildFailureResult("该邮箱不存在！");
		}
		Email mail=new Email();
		mail.setToUser(email);
		mail.setSubject("ERP使用者密码重置，请勿回复此邮件");
		Random random=new Random();
		Integer code=random.nextInt(9000) + 1000;
		String key=Constant.REDIS_PRIFIX_ERP+email;
		logger.info("忘记密码发送email:"+email+";随机码：code="+code+";redis的key为："+key);
		JedisUtils.set(key, code.toString(),1800);
		mail.setContent("<h2>欢迎使用ERP服务系统，</h2><br/>"
				+ "<h2>您本次的验证码为：<b>"+code.toString()+"</b>,</h2><br/>"
				+ "<h2>请在30分钟内使用！</h2><br/>"
				+ "<h2>再次感谢您的使用！</h2><br/>"
				+ "<h1>ERP服务系统团队敬上！</h1>");
		mailService.sendHTMLMail(mail);
		return OperationResult.buildSuccessResult();
	}

	public OperationResult getAllRegions() {
		List<Area> list = regionService.getRegion();
		List<Area> provincialList = list.stream().filter(region->region.getLevelType()==1).collect(Collectors.toList());
		List<Area> cityList = list.stream().filter(region->region.getLevelType()==2).collect(Collectors.toList());
		List<Area> regionList = list.stream().filter(region->region.getLevelType()==3).collect(Collectors.toList());
		for (Area city : cityList) {
			long parenId=city.getValue();
			city.setList(regionList.stream().filter(region->region.getParentId()==parenId).collect(Collectors.toList()));
		}
		for (Area provincial : provincialList) {
			long parenId=provincial.getValue();
			provincial.setList(cityList.stream().filter(region->region.getParentId()==parenId).collect(Collectors.toList()));
		}
		return OperationResult.buildSuccessResult(provincialList);
		
	}

	public OperationResult getExpert(Long serverId, String type,HttpServletRequest request) {
		AppUser appUser=AppUserUtils.getCurrentUser(request);
		String order="create_date";
		if(appUser!=null&&"1".equals(type)){
			order="sum_answers";
			List<ExpertUser> list = expertUserService.findByCustomSort(serverId,appUser.getId(),order);
			if(list==null||list.isEmpty()){
				return OperationResult.buildSuccessResult(expertUserService.findByCustomSort(serverId,null,order));
			}
			return OperationResult.buildSuccessResult(list);
		}
		if("2".equals(type)){//答疑最多
			order="sum_answers desc";
		}else if("3".equals(type)){//年限最多
			order="years desc";
		}
		return OperationResult.buildSuccessResult(expertUserService.findByCustomSort(serverId,null,order));
	}

	public OperationResult getRegionById(Long id) {
		return OperationResult.buildFailureResult(regionService.getRegionById(id));
	}

	public OperationResult activate(String activateCode, Long id) {
		AppUser appUser=appUserService.get(id);
		if(Constant.USER_IS_ACTIVATED.equals(appUser.getIsActivate())){
			return OperationResult.buildFailureResult("已经激活,请勿重复激活!");
		}
        if(StringUtils.isBlank(activateCode)){
        	return OperationResult.buildFailureResult("激活验证码不能为空！");
        }
        if(!activateCode.equals(appUser.getActivateCode())){
        	return OperationResult.buildFailureResult("激活码有误,请检查输入的URL是否正确！也可以联系客服人员");
        }
        //验证成功，将状态改为激活
        appUser.setIsActivate(Constant.USER_IS_ACTIVATED);
        appUserService.update(appUser);
		return OperationResult.buildSuccessResult("激活成功！");
	}
	
	public OperationResult getServerType() {
		List<Server> list = serverService.findAllList();
		List<Server> parentList = list.stream().filter(server->server.getParentId()==0l).collect(Collectors.toList());
		for (Server ser : parentList) {
			Long id=ser.getId();
			ser.setLists(list.stream().filter(server->server.getParentId()==id).collect(Collectors.toList()));
		}
		return OperationResult.buildSuccessResult(parentList);
	}

	public OperationResult upload(MultipartFile file) {
		if(file==null){
			return OperationResult.buildFailureResult("上传文件不能为空！");
		}
		 String fileName = file.getOriginalFilename();
	     fileName = FileUtil.renameToUUID(fileName);
	     File sysFile = new File(FileType.fileType(fileName), "/files/" + fileName, new Date());
	     try {
			FileUtil.uploadFile(file, bootdoConfig.getUploadPath(), fileName);
		} catch (Exception e) {
			logger.error("上传头像失败！",e);
			return OperationResult.buildFailureResult("上传头像失败！");
		}
	    sysFileService.save(sysFile);
	    Map<String, Object>data=new HashMap<String, Object>();
	    data.put("fileUrl", sysFile.getUrl());
		return OperationResult.buildSuccessResult(data);
	}

	public OperationResult downlodInfo() {
		 Map<String, Object>data=new HashMap<String, Object>();
		 List<Map<String, Object>>downList=new ArrayList<Map<String,Object>>();
		 Map<String, Object>down=new HashMap<String, Object>();
		 down.put("name", "XT800远程控制工具");
		 down.put("url", "/files/8b6c51b7-4ab7-4b4f-a2bd-150a05fa9223.zip");
		 downList.add(down);
		 data.put("downList",downList);
		// TODO Auto-generated method stub
		return OperationResult.buildSuccessResult(data);
	}
}
